package com.markerhub.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.markerhub.common.dto.CourseUpdateDto;
import com.markerhub.common.dto.StudentUpdateDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.*;
import com.markerhub.service.ManagerStudentService;
import com.markerhub.service.UserService;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;

@Slf4j
@RestController
@RequestMapping("/manager-student")
public class ManagerStudentController {
    @Autowired
    ManagerStudentService studentService;
@Autowired
    UserService userService;

    @RequiresRoles("admin")
    @RequiresAuthentication
    @GetMapping("/search")
    public Result list(String stuName,
                       @RequestParam(defaultValue = "1") Integer currentPage,
                       @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            Page<ManagerStudent> page = new Page<>(currentPage, pageSize);
            LambdaQueryWrapper<ManagerStudent> wrapper = new LambdaQueryWrapper<>();
            // 添加用户名模糊搜索条件
            if (StrUtil.isNotBlank(stuName)) {
                wrapper.like(ManagerStudent::getStuName, stuName);
            }
            // 按创建时间降序排序

            IPage<ManagerStudent> stuPage = studentService.page(page, wrapper);
            return Result.succ(stuPage);
        } catch (Exception e) {
            log.error("获取用户列表失败:", e);
            return Result.fail("获取用户列表失败");
        }
    }


    @RequiresAuthentication
    @GetMapping("/students")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page page = new Page(currentPage, 5);
        IPage pageData = studentService.page(page, new QueryWrapper<ManagerStudent>());
        return Result.succ(pageData);
    }

    @RequiresAuthentication
    @GetMapping("/all")
    public Result getAllStudents() {
        List<ManagerStudent> students = studentService.list();
        return Result.succ(students);
    }

    @RequiresAuthentication
    @PostMapping("/update")
    public Result saveOrUpdateCourse(@RequestBody StudentUpdateDto studentUpdateDto) {
        log.info("Student Update DTO: " + studentUpdateDto);

        Long loginId = null;
        if (studentUpdateDto.getLoginId() == null) {
            User newUser = new User();
            newUser.setRole("student");  // 设置默认角色为 student
            newUser.setStatus(1);  // 默认启用
            // 保存新用户到数据库
            userService.saveOrUpdate(newUser);
            // 获取新创建的用户的 ID
            loginId = newUser.getId();
        }
        // 创建或更新学员信息
        ManagerStudent student = new ManagerStudent();
        if (studentUpdateDto.getId() != null) {
            student.setId(studentUpdateDto.getId());  // 更新已有学员
        }
        student.setStatus(studentUpdateDto.getStatus());
        student.setComment(studentUpdateDto.getComment());
        student.setCurrentGrade(studentUpdateDto.getCurrentGrade());
        student.setStuName(studentUpdateDto.getStuName());
        student.setFromPlace(studentUpdateDto.getFromPlace());
        student.setIsFirst(studentUpdateDto.getIsFirst());
        student.setParentPhone(studentUpdateDto.getParentPhone());
        student.setLoginId(loginId);  // 设置loginId，可能是新创建的用户ID
        // 保存或更新学员信息
        studentService.saveOrUpdate(student);
        return Result.succ("新增保存成功");
    }

    @RequiresAuthentication
    @DeleteMapping("/delete/{id}")
    public Result deleteStudent(@PathVariable Long id) {
        boolean isDeleted = studentService.removeById(id);
        if (isDeleted) {
            return Result.succ("学员删除成功");
        } else {
            return Result.fail("学员删除失败，课程不存在");
        }
    }

    @RequiresAuthentication
    @PostMapping("/batch-audit")
    public Result batchAudit(@RequestBody Map<String, List<Integer>> data) {
        List<Integer> studentIds = data.get("studentIds"); // 获取传过来的学生 ID 列表
        if (studentIds == null || studentIds.isEmpty()) {
            return Result.fail("学生 ID 列表不能为空");
        }
        try {
            studentService.batchAudit(studentIds);
            return Result.succ("批量审核成功");
        } catch (Exception e) {
            return Result.fail("批量审核失败: " + e.getMessage());
        }
    }



    @RequiresAuthentication
    @PostMapping("/import")
    public Result importStudents(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要上传的文件");
        }

        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            List<ManagerStudent> students = new ArrayList<>();

            // 从第二行开始读取（跳过表头）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 创建新用户
                User newUser = new User();
                newUser.setRole("student");
                newUser.setStatus(1);
                userService.save(newUser);
                Long loginId = newUser.getId();

                // 创建学生对象
                ManagerStudent student = new ManagerStudent();
                student.setStuName(getCellValueAsString(row.getCell(0)));
                student.setFromPlace(getCellValueAsString(row.getCell(1)));
                student.setParentPhone(getCellValueAsString(row.getCell(2)));
                student.setCurrentGrade(getCellValueAsString(row.getCell(3)));
                student.setIsFirst(getCellValueAsString(row.getCell(4)));
                student.setStatus(getCellValueAsString(row.getCell(5)));
                student.setComment(getCellValueAsString(row.getCell(6)));
                student.setLoginId(loginId);

                students.add(student);
            }

            studentService.saveBatch(students);

            return Result.succ("成功导入 " + students.size() + " 条数据");
        } catch (IOException e) {
            log.error("文件导入失败", e);
            return Result.fail("文件导入失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("数据处理失败", e);
            return Result.fail("数据处理失败：" + e.getMessage());
        }
    }

    // 工具方法：获取单元格的字符串值
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                }
                return String.valueOf((int) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }
}
